<template>
  <a-modal
    v-model="importVisible"
    title="导入ECU装配车辆"
    width="1000px"
    dialogClass="createFormStyle"
    :bodyStyle="{ height: '500px', overflowY: 'auto' }"
  >
    <template slot="footer">
      <a-button @click="importVisible = false" type="primary">{{ $t('back') }}</a-button>
    </template>
    <div>
      <a-input
        class="formFileInput"
        :placeholder="$t('formatFiles')"
        readOnly
        :value="importFile"
        style="width:400px;margin-right: 10px"
      >
        <template #addonAfter>
          <i class="iconfont icon-shangchuan" @click="$refs.upload.uploadDo()"></i>
        </template>
      </a-input>
      <a-button
        @click="downloadTemplate"
        :loading="downloading"
      >{{ $t('downloadTemplate') }}</a-button>
      <div>
        <template v-if="uploadRes.fail.length > 0">
          <h4 style="margin-top:20px;color:red">失败明细(共{{uploadRes.failCount}}条)：</h4>
          <a-table
            ref="importFailTable"
            class="h100 withMinHeightTbodyBox"
            :rowKey="(record, index) => 'fail-' + index"
            :columns="importFailColumns"
            :data-source="uploadRes.fail"
            :scroll="{x:300}"
            :pagination="false"
          >
            <span slot="message" slot-scope="message" style="color:red;white-space: pre-line">
                {{ message }}
            </span>
          </a-table>
        </template>
        <template v-if="uploadRes.success.length > 0">
          <h4 style="margin-top:20px;">导入成功(共{{uploadRes.successCount}}条)：</h4>
          <a-table v-if="uploadRes.success.length > 0"
                   ref="importSuccessTable"
                   class="h100 withMinHeightTbodyBox"
                   :rowKey="(record, index) => 'suc-' + index"
                   :columns="importSuccessColumns"
                   :data-source="uploadRes.success"
                   :pagination="false"
          >
          </a-table>
        </template>
      </div>
      <!-- 来自文件上传 -->
      <local-upload
        ref="upload"
        :domView="false"
        @showFileObj="showFileObj"
        :accept="['.xls','.xlsx']"
      ></local-upload>
    </div>
  </a-modal>
</template>
<script>
import { downloadBlobFile } from '@/utils/functions'
import LocalUpload from '@/components/Upload/LocalUpload'

export default {
  components: {
    LocalUpload
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    ecuModuleId: {
      type: String,
      default: ''
    },
    cols: {
      type: Array,
      default: []
    },
  },
  computed: {
    importVisible:{
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit('change', val);    // 触发
        // this.changeOption(val)
      }
    }
  },
  data () {
    var data = {
      importFile:'',
      uploadRes:{
        fail: [],
        success: [],
        failCount: 0,
        successCount: 0,
      },
      exporting: false,
      downloading: false,
    }
    data.importFailColumns = [...this.cols, {
      title: '失败原因',
      dataIndex: 'message',
      width: 200,
      fixed: 'right',
      scopedSlots: { customRender: 'message' }
    }];
    data.importSuccessColumns = [...data.importFailColumns];
    data.importSuccessColumns.splice(data.importSuccessColumns.length - 1, 1);
    return data
  },
  model: {
    prop: "visible", //绑定的值，通过父组件传递
    event: "change" //自定义事件名
  },
  created () {

  },
  watch: {
    visible (val) {
      if (!val) {
        this.importFile = '';
        this.uploadRes.fail=[];
        this.uploadRes.success=[];
      }
    }
  },
  methods: {
    downloadTemplate() {
      this.downloading = true
      this.$api.importTemplate('ecuVin').then((res) => {
        downloadBlobFile(res, 'ECU装配车辆VIN导入模板.xlsx')
      }).finally(() => {
        this.downloading = false
      })
    },
    showFileObj (value) {
      const vm = this
      vm.importFile = value.name
      const formData = new FormData()
      formData.append('file', value)
      formData.append('ecuModuleId', this.ecuModuleId)
      this.uploadRes.fail = [];
      this.uploadRes.failCount = 0;
      this.uploadRes.success = [];
      this.uploadRes.successCount = 0;
      vm.$api.uploadEcuVehicleVinExcel(formData).then(res => {
        if (res.data) {
          if(res.data.fail){
            res.data.fail.forEach((item) => {
              vm.uploadRes.fail = [...vm.uploadRes.fail, {
                vin : item.data,
                message : item.message,
              }];
            })
            vm.uploadRes.failCount = vm.uploadRes.fail.length;
            // 截取500条
            vm.uploadRes.fail.splice(500);
          }
          if(res.data.success){
            res.data.success.forEach((item) => {
              vm.uploadRes.success = [...vm.uploadRes.success, {vin : item.data}];
            })
            vm.uploadRes.successCount = vm.uploadRes.success.length;
            vm.uploadRes.success.splice(500);
          }
          if (vm.uploadRes.successCount === 0 && vm.uploadRes.failCount === 0) {
            vm.$message.error("没有数据！");
          }
          if (vm.uploadRes.successCount > 0) {
            this.refreshData(false);
          }
        }
      }).catch(() => {
        vm.importFile = ''
      })
    },
  }
}
</script>
<style lang="less">
.importCarForm {
  .ant-form-item {
    margin-bottom: 0;
  }
  .importCarBtn {
    width: 100%;
  }
}
</style>
<style scoped lang="less">
.uploadResultCol {
  margin-top: 15px;
  span {
    margin-right: 15px;
  }
  .uploadResultTitle {
    font-size: 14px;
    font-weight: bold;
  }
}
</style>
